package com.chat.controller;

import com.chat.entity.Friend;
import com.chat.entity.Message;
import com.chat.service.friend.FriendService;
import com.chat.service.message.MessageService;
import com.chat.util.ResponseUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

@Controller
public class MessageController {
    @Autowired
    private MessageService messageService;

    @Autowired
    private FriendService friendService;

    /**
     * 获取和好友的消息列表
     * @param userEmail 用户邮箱
     * @param friendEmail 朋友邮箱
     * @return 在服务器上的消息列表
     */
    @RequestMapping(value = "/message/getMessages.do",method = RequestMethod.GET)
    @ResponseBody
    public List<Message> getMessages(String userEmail, String friendEmail){
        List<Message> list=messageService.getMessages(userEmail, friendEmail);
        for(Message msg:list){
            msg.setSourceUser(null);
            msg.setTargetUser(null);
        }

        return  list;
    }

    /**
     * 删除消息端口
     * @param id 消息id
     * @return 返回是否成功
     */
    @RequestMapping(value = "/message/deleteMessage.do",method = RequestMethod.GET)
    @ResponseBody
    public Map deleteMessage(String id){
        long msgId;

        try {
            msgId=new Long(id);
        }catch (Exception ex){
            return ResponseUtil.getFailureResponse("消息ID错误");
        }

        messageService.deleteMessage(msgId);

        return ResponseUtil.getSuccessResponse();
    }

    /**
     * 发送消息端口
     * @param userEmail 用户邮箱
     * @param friendEmail 好友邮箱
     * @param msg 消息内容
     * @return
     */
    @RequestMapping(value = "/message/sendMessage.do",method = RequestMethod.GET)
    @ResponseBody
    public Map sendMessage(String userEmail,String friendEmail,String msg){
        Friend friend=friendService.getFriend(userEmail,friendEmail);

        if(friend==null){
            return ResponseUtil.getFailureResponse("两人不是好友关系!");
        }

        if(friend.getSendCount()>friend.getFeeling()/10+9){
            return ResponseUtil.getFailureResponse("已经达到了今天的消息发送上限");
        }

        //发送消息并增加好感度
        messageService.sendMessage(userEmail,friendEmail,msg);
        friend.setFeeling(friend.getFeeling()+1);

        return ResponseUtil.getSuccessResponse();
    }
}
